package controller

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"ylb/entity"
	"ylb/interceptor"
	"ylb/service/impl"
	"ylb/tool"
)

type NoteController struct {
	service impl.NoteServiceImpl
}

func NewNoteController(gin *gin.Engine) NoteController {
	controller := NoteController{}
	controller.service = impl.NewNoteServiceImpl()
	controller.NoteRoute(gin)
	return controller
}

func (note NoteController) NoteRoute(gin *gin.Engine) {

	group := gin.Group("/note")
	group.Use(interceptor.TokenInterceptor())
	{
		group.POST("/save", note.saveNote)
		group.GET("/get", note.getNote)
	}
}

func (note NoteController) saveNote(context *gin.Context) {
	id := GetUserId(context)
	m := map[string]string{}
	err := context.BindJSON(&m)
	if err != nil {
		fmt.Printf("%v\n", err)
		return
	}
	content := m["note"]
	fmt.Printf("content: %v\n", content)

	update := note.service.SaveNote(entity.Note{
		UserId:  id,
		Content: content,
	})

	if update == 0 {
		context.JSON(http.StatusOK, tool.Error("失败", gin.H{}))
	} else {
		context.JSON(http.StatusOK, tool.Success("成功", gin.H{}))
	}

}
func (note NoteController) getNote(context *gin.Context) {

	id := GetUserId(context)
	n := note.service.SelectNoteByUserId(id)
	context.JSON(http.StatusOK, tool.Success("成功", gin.H{
		"note": n,
	}))

}
